package com.feather.tenia.mysql;

import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.feather.common.data.DataSet;
import com.feather.common.data.DataTable;
import com.feather.common.data.simple.SimpleColumn;
import com.feather.tenia.adapter.ProcedureAdapter;
import com.feather.tenia.mysql.fetcher.CURSOR_Fetcher;
import com.feather.tenia.ProcedureMeta;
import com.feather.tenia.Tenia;

/**
 * @author flogyin
 */
public class MysqlProcedure extends ProcedureAdapter {
	protected CURSOR_Fetcher	cursorFetcher;

	public MysqlProcedure(Tenia dbTenia, ProcedureMeta meta) {
		super(dbTenia, meta);
		this.cursorFetcher = new CURSOR_Fetcher(dbTenia);
	}

	@Override
	protected long[] execute(CallableStatement statement, DataSet dataSet) throws SQLException {
		long currentMs = System.currentTimeMillis();
		boolean hadResults = statement.execute();
		long overExecuteMs = System.currentTimeMillis();

		SimpleColumn column = new SimpleColumn();
		column.setCatalog(super.meta.getCatalog());
		int order = 1;
		while (hadResults) {
			column.setName("table" + order++);
			ResultSet rs = statement.getResultSet();
			DataTable dataTable = (DataTable) this.cursorFetcher.fetch(rs, column);
			dataSet.getResult().add(dataTable);
			hadResults = statement.getMoreResults();
		}
		return new long[] { overExecuteMs - currentMs, System.currentTimeMillis() - overExecuteMs };
	}
}
